package com.acce.gxsc.page.outCar.detail.batchDetail;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.acce.gxsc.R;
import com.acce.gxsc.common.App;
import com.acce.gxsc.common.DateUtils;
import com.acce.gxsc.common.Tools;
import com.acce.gxsc.model.netBean.BatchBean;
import com.acce.gxsc.model.netBean.InCarBean;
import com.acce.gxsc.model.netBean.InCarGoodsBean;
import com.acce.gxsc.model.netBean.NetOutCarBatchDetailBean;
import com.acce.sdk.User;
import com.acce.sdk.base.mvp.BaseMvpActivity;
import com.acce.sdk.utils.StringUtils;
import com.acce.sdk.utils.ToastUtils;
import com.acce.sdk.widget.AcceBar;
import com.acce.sdk.widget.EditWithTitle;
import com.acce.sdk.widget.adapterrv.ViewHolder;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by huxley on 2017/5/26.
 */

public class OutCarBatchDetailActivity extends BaseMvpActivity<OutCarBatchDetailView, OutCarBatchDetailPresenter> implements OutCarBatchDetailView {

    String queryId = "";
    boolean        isOutCar;
    LayoutInflater inflater;
    ViewHolder     holder;

    @Bind(R.id.ll_root)
    LinearLayout mLlRoot;
    @Bind(R.id.accebar)
    AcceBar      mAccebar;
    @Bind(R.id.tv_car_weight)
    TextView     mTvCarWeight;

    @Override
    protected OutCarBatchDetailPresenter createPresenter() {
        return new OutCarBatchDetailPresenter();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.out_car_batch_detail_activity);
        ButterKnife.bind(this);
        inflater = LayoutInflater.from(this);
        if (getIntent().hasExtra("queryId")) {
            queryId = getIntent().getStringExtra("queryId");
        }
        if (getIntent().hasExtra("isOutCar")) {
            isOutCar = getIntent().getBooleanExtra("isOutCar", false);
        }
        mAccebar.setTitleText(isOutCar ? "离场车辆登记详情" : "监察车辆登记详情");
        holder = new ViewHolder(this, mLlRoot);
        mPresenter.loadOutCarDetail(queryId);
    }

    private void setData(final NetOutCarBatchDetailBean inBatchListBean) {
        if (inBatchListBean != null) {
            final InCarBean incarInfo = inBatchListBean.inCar;
            if (incarInfo != null) {
                holder.setText(R.id.tv_in_car_id, Tools.getString(incarInfo.inCarId));
                holder.setText(R.id.tv_dilivery_type, Tools.getString(incarInfo.diliveryType));
                holder.setText(R.id.tv_plate_num, Tools.getString(incarInfo.plateNum));
                holder.setText(R.id.tv_contain_no, Tools.getString(incarInfo.containNo));
                holder.setText(R.id.tv_hang_num, Tools.getString(incarInfo.hangNum));
                holder.setText(R.id.tv_create_time, Tools.getTime(incarInfo.createTime));
                holder.setText(R.id.tv_stay_time, Tools.getStayTime1(incarInfo.createTime));
                holder.setText(R.id.tv_park_area, Tools.getString(incarInfo.parkArea));
                holder.setText(R.id.tv_confirm_gate_name, Tools.getString(incarInfo.confirmGateName));
                holder.setText(R.id.tv_confirm_registrant, Tools.getString(incarInfo.confirmRegistrant));
                holder.setText(R.id.tv_confirm_register_time, Tools.getTime(incarInfo.confirmRegisterDate, incarInfo.confirmRegisterTime));
                holder.setText(R.id.tv_in_car_gate_no, Tools.getString(incarInfo.inCarGateNo));
                holder.setText(R.id.tv_in_car_registrant, Tools.getString(incarInfo.inCarRegistrant));
                holder.setText(R.id.tv_charge_total, Tools.getChargeTotal(inBatchListBean));
                holder.setText(R.id.tv_create_time_1, Tools.getTime(incarInfo.createTime));
                holder.setText(R.id.tv_car_weight, Tools.getString(incarInfo.carWeight));
                holder.setText(R.id.tv_car_type, Tools.getString(incarInfo.carType));
                LinearLayout llContent = holder.getView(R.id.ll_content);
                llContent.removeAllViews();
                ArrayList<BatchBean> inBatchList = inBatchListBean.inBatch;
                boolean isEnable = false;
                if (inBatchList != null && !inBatchList.isEmpty()) {
                    for (BatchBean batchBean : inBatchList) {
                        View child = inflater.inflate(R.layout.out_car_batch_detail_item_batch, llContent, false);
                        ViewHolder childHolder = new ViewHolder(this, child);
                        childHolder.setText(R.id.tv_contact_name, Tools.getString(batchBean.contactName));
                        childHolder.setText(R.id.tv_under_company, Tools.getString(batchBean.underCompany));
                        childHolder.setText(R.id.tv_goods_type_info, Tools.getString(batchBean.goodsTypeInfo));
                        childHolder.setText(R.id.tv_goods_info, Tools.getString(batchBean.goodsInfo));
                        childHolder.setText(R.id.tv_fee2_id, Tools.getFee2Id(batchBean.fee2Id));
                        childHolder.setText(R.id.tv_fee3_id, Tools.getFee3Id(batchBean.fee3Id));
                        isEnable = isEnable || Tools.getEnable(batchBean.fee2Id, batchBean.fee3Id);
                        childHolder.setBackgroundColor(R.id.ll_fee, Tools.getStateColor(batchBean.fee2Id, batchBean.fee3Id));
                        llContent.addView(child);
                        LinearLayout llBatch = holder.getView(R.id.ll_batch);
                        llBatch.removeAllViews();
                        ArrayList<InCarGoodsBean> inGoods = batchBean.inGoods;
                        if (inGoods != null && !inGoods.isEmpty()) {
                            for (InCarGoodsBean goodsBean : batchBean.inGoods) {
                                View goodsChild = inflater.inflate(R.layout.out_car_batch_detail_item_fee, llBatch, false);
                                ViewHolder goodsHolder = new ViewHolder(this, goodsChild);
                                goodsHolder.setText(R.id.tv_goods_type, Tools.getString(goodsBean.goodsType));
                                goodsHolder.setText(R.id.tv_goods_name, Tools.getString(goodsBean.goodsName));
                                goodsHolder.setText(R.id.tv_price_type, Tools.getString(goodsBean.priceType));
                                goodsHolder.setText(R.id.tv_charge_category, Tools.getString(goodsBean.chargeCategory));
                                goodsHolder.setText(R.id.tv_goods_remarks, Tools.getString(goodsBean.remarks));
                                goodsHolder.setText(R.id.tv_charge_total, Tools.getString(goodsBean.chargeTotal));
                                goodsHolder.setText(R.id.tv_plate_amount, Tools.getString(goodsBean.plateAmount));
                                goodsHolder.setText(R.id.tv_amount, Tools.getString(goodsBean.amount));
                                goodsHolder.setText(R.id.tv_charge_price, Tools.getPrice(goodsBean.chargePrice, goodsBean.chargeUnit));
                                llBatch.addView(goodsChild);
                            }
                        }
                    }
                }
                if (isOutCar) {
                    if (isEnable) {
                        holder.getView(R.id.tv_2).setEnabled(false);
                        holder.setBackgroundRes(R.id.tv_2, R.color.color_e4e4e4);
                        holder.setText(R.id.tv_2, "允许离场");
                    } else {
                        if ("1".equals(incarInfo.outCarStatus)) {
                            holder.getView(R.id.tv_2).setEnabled(false);
                            holder.setBackgroundRes(R.id.tv_2, R.color.color_e4e4e4);
                            holder.setText(R.id.tv_2, "已离场");
                            holder.getView(R.id.tv_1).setEnabled(false);
                            holder.setBackgroundRes(R.id.tv_1, R.color.color_e4e4e4);
                            holder.setText(R.id.tv_1, "已离场");
                        } else {
                            holder.getView(R.id.tv_2).setEnabled(true);
                            holder.setBackgroundRes(R.id.tv_2, R.color.color_39ca74);
                            holder.setText(R.id.tv_2, "允许离场");
                        }
                    }
                    holder.setText(R.id.tv_remarks_title, "离场备注：");
                    holder.setText(R.id.tv_remarks, Tools.getString(incarInfo.outCarRemarks));
                    holder.setText(R.id.tv_1, "填报离场差异信息");
                    holder.setBackgroundRes(R.id.tv_1, R.color.color_FD9840);
                    holder.setTextColorRes(R.id.tv_1, R.color.white);
                    holder.setTextColorRes(R.id.tv_2, R.color.white);
                    holder.setOnClickListener(R.id.tv_1, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            diffOutCar(incarInfo.inCarId);
                        }
                    });
                    holder.setOnClickListener(R.id.tv_2, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            outCar(incarInfo.inCarId);
                        }
                    });
                } else {
                    if ("1".equals(incarInfo.superviseOther)) {
                        holder.getView(R.id.tv_2).setEnabled(false);
                        holder.setBackgroundRes(R.id.tv_2, R.color.color_e4e4e4);
                        holder.setText(R.id.tv_2, "已监察");
                        holder.getView(R.id.tv_1).setEnabled(false);
                        holder.setBackgroundRes(R.id.tv_1, R.color.color_e4e4e4);
                        holder.setText(R.id.tv_1, "已监察");
                    } else {
                        holder.getView(R.id.tv_2).setEnabled(true);
                        holder.setBackgroundRes(R.id.tv_2, R.color.celestial_blue);
                        holder.setText(R.id.tv_2, "提交监察报告");
                    }
                    holder.setText(R.id.tv_remarks_title, "监察备注：");
                    holder.setText(R.id.tv_remarks, Tools.getString(incarInfo.superviseRemarks));
                    holder.setText(R.id.tv_1, "填报监察差异信息");
                    holder.setBackgroundRes(R.id.tv_1, R.color.color_FD9840);
                    holder.setTextColorRes(R.id.tv_1, R.color.white);
                    holder.setTextColorRes(R.id.tv_2, R.color.white);
                    holder.setOnClickListener(R.id.tv_1, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            diffSupervisionCar(incarInfo.inCarId);
                        }
                    });
                    holder.setOnClickListener(R.id.tv_2, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            supervisionCar(incarInfo.inCarId);
                        }
                    });
                }
                holder.setOnClickListener(R.id.tv_3, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        printSupervise(inBatchListBean);
                    }
                });
            }
        }
    }

    private void printSupervise(NetOutCarBatchDetailBean inBatchListBean) {
        ScrollView rootView = (ScrollView) inflater.inflate(R.layout.out_car_batch_detail_activity_dialog_print, (ViewGroup) findViewById(R.id.dialog));
        final LinearLayout llContent = ButterKnife.findById(rootView, R.id.ll_content);
        final ViewHolder holderCar = new ViewHolder(this, llContent);
        holderCar.setText(R.id.tv_time, Tools.getString(DateUtils.getTime4()));
        holderCar.setText(R.id.tv_duty_id, Tools.getString(App.dutyId));
        holderCar.setText(R.id.tv_incar_registrant, Tools.getString(User.getInstance().getRealName()));
        holderCar.setText(R.id.tv_order_title, isOutCar ? "市场离场报告单" : "市场监察报告单");
        holderCar.setText(R.id.tv_1, isOutCar ? "离场班长签名:" : "监察班长签名:");
        holderCar.setText(R.id.tv_2, isOutCar ? "离场员签名:" : "监察员签名:");
        if (inBatchListBean != null) {
            final InCarBean incarInfo = inBatchListBean.inCar;
            if (incarInfo != null) {
                holderCar.setText(R.id.tv_create_time, Tools.getTime(incarInfo.createTime));
                holderCar.setText(R.id.tv_in_car_registrant, Tools.getString(incarInfo.inCarRegistrant));
                holderCar.setText(R.id.tv_confirm_register_time, Tools.getString(incarInfo.inCarRegistrant));
                holderCar.setText(R.id.tv_confirm_registrant, Tools.getString(incarInfo.confirmRegistrant));
                holderCar.setText(R.id.tv_confirm_register_time, Tools.getTime(incarInfo.confirmRegisterDate, incarInfo.confirmRegisterTime));
                holderCar.setText(R.id.tv_in_car_id, Tools.getString(incarInfo.inCarId));
                holderCar.setText(R.id.tv_dilivery_type, Tools.getString(incarInfo.diliveryType));
                holderCar.setText(R.id.tv_plate_num, Tools.getString1(incarInfo.plateNum, incarInfo.containNo));
                holderCar.setText(R.id.tv_hang_num, Tools.getString(incarInfo.hangNum));
                holderCar.setText(R.id.tv_under_company, Tools.getString(incarInfo.underCompany));
                holderCar.setText(R.id.tv_supervise_time, Tools.getTime(incarInfo.superviseRegisterDate, incarInfo.superviseRegisterTime));
                holderCar.setText(R.id.tv_supervise_duty_id, Tools.getString(incarInfo.superviseDutyId));
                holderCar.setText(R.id.tv_supervise_registrant, Tools.getString(incarInfo.superviseRegistrant));
                String superviseRemarks = incarInfo.superviseRemarks;
                if (superviseRemarks!=null) {
                    String[] split = superviseRemarks.split("/");
                    if (split.length>=5) {
                        holderCar.setText(R.id.tv_supervise_plate_num, String.format("车牌号码：%s", Tools.getString(split[0])));
                        holderCar.setText(R.id.tv_supervise_contain_no, Tools.getString(split[1]));
                        holderCar.setText(R.id.tv_supervise_hang_num,  String.format("挂号：%s", Tools.getString(split[2])));
                        holderCar.setText(R.id.tv_supervise_park_area, Tools.getString(split[3]));
                        holderCar.setText(R.id.tv_supervise_goods_info, Tools.getString(split[4]));
                        if (split.length>=6) {
                            holderCar.setText(R.id.tv_supervise_remarks, Tools.getString(split[5]));
                        }
                    }
                }
                final LinearLayout llBatch = holderCar.getView(R.id.ll_batch);
                llBatch.removeAllViews();
                ArrayList<BatchBean> inBatchList = inBatchListBean.inBatch;
                int batchCount = 0;
                if (inBatchList != null && !inBatchList.isEmpty()) {
                    batchCount = inBatchList.size();
                    for (BatchBean batchBean : inBatchList) {
                        View viewBatch = inflater.inflate(R.layout.out_car_batch_detail_activity_dialog_print_item_batch, llContent, false);
                        ViewHolder holderBatch = new ViewHolder(this, viewBatch);
                        holderBatch.setText(R.id.tv_inbatch_id, Tools.getString(batchBean.inBatchId));
                        holderBatch.setText(R.id.tv_fee2_id, Tools.getFee2Id(batchBean.fee2Id));
                        holderBatch.setText(R.id.tv_fee3_id, Tools.getFee3Id(batchBean.fee3Id));
                        holderBatch.setText(R.id.tv_park_area, Tools.getString(batchBean.parkArea));
                        holderBatch.setText(R.id.tv_contact_name, Tools.getString(batchBean.contactName));
                        holderBatch.setText(R.id.tv_total, Tools.getChargeTotal1(inBatchListBean, batchBean.inBatchId));
                        llBatch.addView(viewBatch);
                        LinearLayout llGoods = holderBatch.getView(R.id.ll_goods);
                        llGoods.removeAllViews();
                        ArrayList<InCarGoodsBean> inGoods = batchBean.inGoods;
                        if (inGoods != null && !inGoods.isEmpty()) {
                            for (InCarGoodsBean goodsBean : batchBean.inGoods) {
                                View viewGoods = inflater.inflate(R.layout.out_car_batch_detail_activity_dialog_print_item_goods, llBatch, false);
                                ViewHolder goodsHolder = new ViewHolder(this, viewGoods);
                                goodsHolder.setText(R.id.tv_goods_type, Tools.getString(goodsBean.goodsType));
                                goodsHolder.setText(R.id.tv_goods_name, Tools.getString(goodsBean.goodsName));
                                goodsHolder.setText(R.id.tv_charge_total, Tools.getString(goodsBean.chargeTotal));
                                goodsHolder.setText(R.id.tv_price_type, Tools.getString(goodsBean.priceType));
                                goodsHolder.setText(R.id.tv_charge_price, Tools.getPrice(goodsBean.chargePrice, goodsBean.chargeUnit));
                                goodsHolder.setText(R.id.tv_goods_remarks, Tools.getString(goodsBean.remarks));
                                goodsHolder.setText(R.id.tv_amount, Tools.getString(goodsBean.amount));
                                llGoods.addView(viewGoods);
                            }
                        }
                    }
                }
                holderCar.setText(R.id.tv_batch_num, String.format("包含%d个批次", batchCount));
            }
        }
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog alertDialog = builder
                .setView(rootView).create();
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.show();
        holderCar.setOnClickListener(R.id.tv_print, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                holderCar.setVisible(R.id.tv_print, false);
                mPresenter.printOrder(llContent);
                alertDialog.dismiss();
            }
        });
    }

    private void supervisionCar(final String inCarId) {
        if (StringUtils.isEmpty(inCarId)) {
            ToastUtils.show("未找到该进场单！");
            return;
        }
        final AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("确定监察？")
                .setNegativeButton("取消", null)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        mPresenter.supervisionCar(inCarId, "");
                    }
                }).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }


    private void outCar(final String inCarId) {
        if (StringUtils.isEmpty(inCarId)) {
            ToastUtils.show("未找到该进场单！");
            return;
        }
        final AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("确定离场？")
                .setNegativeButton("取消", null)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        mPresenter.toOutCar(inCarId, "");
                    }
                }).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    private void diffSupervisionCar(final String inCarId) {
        if (StringUtils.isEmpty(inCarId)) {
            ToastUtils.show("未找到该进场单！");
            return;
        }
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_diff_supervision, (ViewGroup) findViewById(R.id.dialog));
        final EditWithTitle ewtCarNo = ButterKnife.findById(layout, R.id.ewt_car_no);
        final EditWithTitle ewtHangNo = ButterKnife.findById(layout, R.id.ewt_hang_no);
        final EditWithTitle ewtBoxNo = ButterKnife.findById(layout, R.id.ewt_box_no);
        final EditWithTitle ewtArea = ButterKnife.findById(layout, R.id.ewt_area);
        final EditWithTitle ewtGoods = ButterKnife.findById(layout, R.id.ewt_goods);
        final EditWithTitle ewtRemark = ButterKnife.findById(layout, R.id.ewt_remark);

        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog alertDialog = builder
                .setView(layout)
                .setTitle("请填写差异信息")
                .setNegativeButton("取消", null)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String carNo = ewtCarNo.getContent();
                        String hangNo = ewtHangNo.getContent();
                        String boxNo = ewtBoxNo.getContent();
                        String area = ewtArea.getContent();
                        String goods = ewtGoods.getContent();
                        String remark = ewtRemark.getContent();
                        if (StringUtils.isEmpty(carNo) && StringUtils.isEmpty(hangNo) && StringUtils.isEmpty(boxNo) && StringUtils.isEmpty(area) && StringUtils.isEmpty(goods) && StringUtils.isEmpty(remark)) {
                            ToastUtils.show("至少填写一项差异信息");
                            return;
                        }
                        mPresenter.supervisionCar(inCarId, Tools.getString4(carNo, hangNo, boxNo, area, goods, remark));
                    }
                }).create();
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.show();
    }


    private void diffOutCar(final String inCarId) {
        if (StringUtils.isEmpty(inCarId)) {
            ToastUtils.show("未找到该进场单！");
            return;
        }
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_diff_out_car, (ViewGroup) findViewById(R.id.dialog));
        final EditWithTitle ewtCarNo = ButterKnife.findById(layout, R.id.ewt_car_no);
        final EditWithTitle ewtHangNo = ButterKnife.findById(layout, R.id.ewt_hang_no);
        final EditWithTitle ewtBoxNo = ButterKnife.findById(layout, R.id.ewt_box_no);
        final EditWithTitle ewtRemark = ButterKnife.findById(layout, R.id.ewt_remark);
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog alertDialog = builder
                .setView(layout)
                .setTitle("请填写差异信息")
                .setNegativeButton("取消", null)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String carNo = ewtCarNo.getContent();
                        String hangNo = ewtHangNo.getContent();
                        String boxNo = ewtBoxNo.getContent();
                        String remark = ewtRemark.getContent();
                        if (StringUtils.isEmpty(carNo) && StringUtils.isEmpty(hangNo) && StringUtils.isEmpty(boxNo)) {
                            ToastUtils.show("至少填写一项差异信息");
                            return;
                        }
                        mPresenter.toOutCar(inCarId, Tools.getString4(carNo, hangNo, boxNo, remark));
                    }
                }).create();
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.show();
    }

    @Override
    public void loadInCarListSuccess(NetOutCarBatchDetailBean inCarList) {
        setData(inCarList);
    }

    @Override
    public void toOutCarSuccess() {
        mPresenter.loadOutCarDetail(queryId);
    }

    @Override
    public void supervisionCarSuccess() {
        mPresenter.loadOutCarDetail(queryId);
    }
}
